package cn.genmer.test.security.leetcode.easy;

/**
 * @program: Algorithm_to_practice
 * 26. 删除有序数组中的重复项
 * @description: 原地删除重复数组
 * @author: Genmer
 * @create: 2020-10-14 17:30
 **/
public class RemoveDuplicateArray {
    public static void main(String[] args) {
//        int[] nums = {0,0,1,1,1,2,2,3,3,4};
        int[] nums = {1,2,2,5};
        int result = removeDuplicates2(nums);
        System.out.println("返回数值为："+result);
        for (int i=0; i<result;i++){
            System.out.println(nums[i]+" ");
        }

    }

    public static int removeDuplicates1(int[] nums) {
        int len = nums.length;
        int result = len;
        int i=0;
        int count=0;
        while(count<len-1){
            count++;
            if (nums[i] == nums[i+1]){
                result--;
               if (i==0){
                   for (int j=i+1; j<len-i-1;j++){
                       nums[j]=nums[j+1];
                   }
               }else {
                   for (int j=i; j<len-i;j++){
                       nums[j]=nums[j+1];
                   }
               }
            } else {
                i++;
            }

        }
        if (i==0) return 1;
        else return result;
    }

    /**
     * 遇到重复使用后面遇到的第一个不重复的值覆盖重复的值
     * @param nums
     * @return
     */
    public static int removeDuplicates2(int[] nums) {
        if (nums.length==0) return 0;
        int i=0;
        for (int j=1;j<nums.length;j++){
            if (nums[i] != nums[j]){
                i++;
                nums[i] = nums[j];
            }
        }
        return i+1;
    }
}
